//
//  CollectionViewController.m
//  ChengXinBao
//
//  Created by RongZhou on 17/3/22.
//  Copyright © 2017年 RongZhou. All rights reserved.
//

#import "CollectionViewController.h"
#import "CompanyInforCell.h"
#import "CompanyInfoModel.h"
#import "CompanyDetailViewController.h"
#import <AFNetworking.h>
@interface CollectionViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *dataArray;
@end

@implementation CollectionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"我的收藏";
    [self createUIAboutTableView];
    [self getDataAboutCollction];
}
-(void)createUIAboutTableView{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight - 64) style:UITableViewStylePlain];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.view addSubview:self.tableView];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
    self.tableView.tableFooterView = view;
    UINib *nib = [UINib nibWithNibName:@"CompanyInforCell" bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:@"CompanyInforCell"];
    
}
-(void)getDataAboutCollction{
    dispatch_queue_t globelQue = dispatch_get_global_queue(0, 0);
    dispatch_async(globelQue, ^{
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        NSString *userId = [[NSUserDefaults standardUserDefaults] objectForKey:@"userId"];
        NSString *str = ServiceUrl@"/collectionApp/searchListByPhoneUserId?id=%@";
        NSString *url = [NSString stringWithFormat:str,userId];
        [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSArray *array = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            for (NSDictionary *dict in array) {
                CompanyInfoModel *model = [[CompanyInfoModel alloc] initWithBackDictionry:dict];
                [self.dataArray addObject:model];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
               [self.tableView reloadData];
            });
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"%@",error);
        }];

    });
}
#pragma mark -tableview的代理方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CompanyInforCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CompanyInforCell"];
    cell.model = self.dataArray[indexPath.row];
    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70.f;
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [self addOrCancelCollection:@"0" andPostion:indexPath];
        [self.dataArray removeObjectAtIndex:indexPath.row];
        //3.刷表
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];

        
    }
}
/**
 *  取消收藏的商户信息
 */
-(void)addOrCancelCollection:(NSString *)judeStr andPostion:(NSIndexPath *)indexpath{
    CompanyInfoModel *model = self.dataArray[indexpath.row];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *url = ServiceUrl@"/collectionApp/addOrCancelCollection";
    NSDictionary *param = @{@"customerId":model.companyId,@"phoneUserId":[[NSUserDefaults standardUserDefaults] objectForKey:@"userId"],@"addOrCancel":judeStr};
    NSLog(@"请求体%@",param);
    [manager POST:url parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        
        NSLog(@"%@",dict);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
    
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    CompanyInfoModel *model = self.dataArray[indexPath.row];
    CompanyDetailViewController *vc = [[CompanyDetailViewController alloc] init];
    vc.companyaddress = model.customerAddr;
    vc.companyname = model.customerName;
    vc.companyphone = model.phoneNumber;
    vc.companyid = model.customerId;
    vc.companylogo = model.logo;
    vc.companyCityname = model.cityName;
    vc.companyAreaname = model.areaName;
    vc.companyWebid = model.companyId;
    vc.companyIntroduce = model.introduce;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark-数据懒加载
-(NSMutableArray *)dataArray{
    if (_dataArray == nil) {
        _dataArray = [[NSMutableArray alloc] init];
    }
    return _dataArray;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
